import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import resumeView from '@/views/resumeView.vue'
import booksView from '@/views/booksView.vue'
import adminhost from '@/views/admin/adminHomeView.vue'
import articlemanage from '@/views/admin/articleManageView.vue'
import admin from '@/views/admin/index.vue'
import restroom from '@/views/admin/restView.vue'
import Login from '@/views/Login.vue'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home',
    },
    {
      path: '/home',
      name: 'Home',
      component: HomeView,
    },
    {
      path: '/login',
      name: 'Login',
      component: Login,
    },
    {
      path: '/resume',
      name: 'resume',
      component: resumeView,
    },
    {
      path: '/projects',
      name: 'projects',
      component: booksView,
    },
    {
      path: '/admin',
      name: 'admin',
      redirect: '/admin/host',
      component: admin,
      children: [
        {
          path: 'host',
          name: 'adminhost',
          component: adminhost,
        },
        {
          path: 'article-manage',
          name: 'article-manage',
          component: articlemanage,
        },
        {
          path: 'restroom',
          name: 'restroom',
          component: restroom,
        },
      ],
    },
  ],
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if ((to.path.startsWith('/home') || to.path.startsWith('/admin')) && !token) {
    next('/login')
  } else {
    next()
  }
})

export default router
